package com.itkjb.leisurely.resource.sys.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itkjb.leisurely.authentication.core.common.support.AuthenticationCache;
import com.itkjb.leisurely.core.base.BaseConstants;
import com.itkjb.leisurely.core.base.BaseDto;
import com.itkjb.leisurely.core.base.BaseResult;
import com.itkjb.leisurely.core.base.controller.BaseController;
import com.itkjb.leisurely.core.model.PageModel;
import com.itkjb.leisurely.core.model.RequestUserInfoModel;
import com.itkjb.leisurely.core.util.RequestUserInfoUtil;
import com.itkjb.leisurely.resource.common.SysConstants;
import com.itkjb.leisurely.resource.sys.model.SysDepartmentModel;
import com.itkjb.leisurely.resource.sys.model.SysUserDepModel;
import com.itkjb.leisurely.resource.sys.model.SysUserModel;
import com.itkjb.leisurely.resource.sys.model.dto.SysUserDepDTO;
import com.itkjb.leisurely.resource.sys.model.dto.UserIdDTO;
import com.itkjb.leisurely.resource.sys.model.vo.SysDepartmentVO;
import com.itkjb.leisurely.resource.sys.model.vo.SysUserVO;
import com.itkjb.leisurely.resource.sys.service.ISysDepartmentService;
import com.itkjb.leisurely.resource.sys.service.ISysUserDepService;
import com.itkjb.leisurely.resource.sys.service.support.DepIdsUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.Serializable;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 用户组织关系对象，组织成员 接口层
 * </p>
 *
 * @author itkjb.com
 * @since 2020-07-17
 */
@RestController
@RequestMapping("/sys/sys-user-dep")
@Api(value="用户组织关系对象，组织成员",tags={"用户组织关系对象，组织成员相关接口"})
public class SysUserDepController extends BaseController<SysUserDepModel,ISysUserDepService> {

    @Autowired
    AuthenticationCache authenticationCache;

    @Autowired
    ISysDepartmentService departmentService;


    /**
     * 获取指定组织的成员列表
     * @param param 查询通用参数
     * @param model 特定条件参数
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/getDepMembers")
    @ApiOperation(value="获取指定组织的成员列表",notes="支持分页参数")
    @PreAuthorize("hasAnyAuthority('SysDepUser','SysDepUser:query') || hasRole('"+ BaseConstants.ADMINISTRATOR_ROLE_CODE +"') ")
    public BaseResult<IPage<SysUserDepModel>> getDepMembers(BaseDto param, SysUserDepDTO model, HttpServletRequest request, HttpServletResponse response){
        BaseResult<IPage<SysUserDepModel>> res = new BaseResult<>();
        if(model==null || StringUtils.isBlank(model.getDepId())){
            return res.setMsg("请先指定组织");
        }
        PageModel<SysUserDepModel> pageModel = new PageModel<>();
        BeanUtils.copyProperties(param, pageModel);
        IPage<SysUserDepModel> depMembers = this.baseService.getDepMembers(pageModel, model);
        res.toSuccess().setData(depMembers);
        return res;
    }

    /**
     * 获取指定组织  可添加的用户列表（即未添加到该组织的用户列表）
     * @param param
     * @param model
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/getNonMembers")
    @ApiOperation(value="获取指定组织  可添加的用户列表（即未添加到该组织的用户列表）",notes="支持分页参数")
    @PreAuthorize("hasAnyAuthority('SysDepUser','SysDepUser:query') || hasRole('"+ BaseConstants.ADMINISTRATOR_ROLE_CODE +"') ")
    public BaseResult<IPage<SysUserVO>> getNonMembers(BaseDto param, SysUserDepDTO model, HttpServletRequest request, HttpServletResponse response){
        BaseResult<IPage<SysUserVO>> res = new BaseResult<>();
        if(model==null || StringUtils.isBlank(model.getDepId())){
            return res.setMsg("请先指定组织");
        }
        PageModel<SysUserModel> pageModel = new PageModel<>();
        BeanUtils.copyProperties(param, pageModel);
        IPage<SysUserVO> depMembers = this.baseService.getNonMembers(pageModel, model);
        res.toSuccess().setData(depMembers);
        return res;
    }

    /**
     * 获取用户组织关系对象，组织成员列表
     * @param param 查询通用参数，分页参数不可用
     * @param model 特定条件参数
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/list")
    @ApiOperation(value="获取用户组织关系对象，组织成员列表",notes="不支持分页")
    @PreAuthorize("hasAnyAuthority('SysDepUser','SysDepUser:query') || hasRole('"+ BaseConstants.ADMINISTRATOR_ROLE_CODE +"') ")
    public BaseResult<List<SysUserDepModel>> list(BaseDto param,SysUserDepModel model, HttpServletRequest request, HttpServletResponse response){
        BaseResult<List<SysUserDepModel>> res = new BaseResult<>();
        // 代码生成器生成的下面执行结果默认关闭，防止获取非法数据和数据量过大，若需要手动打开，并做好防护措施
        // return super.list(param, model);
        res.toSuccess().setMsg("注意：无结果返回，默认关闭list查询");
        return res;
    }

    @GetMapping("/userDeps")
    @ApiOperation(value="获取某用户所在所有组织的成员信息",notes="不支持分页")
    @PreAuthorize("hasAnyAuthority('SysDepUser:info','SysUser:SysDepUser:info') || hasRole('"+ BaseConstants.ADMINISTRATOR_ROLE_CODE +"') ")
    public BaseResult<List<SysUserDepModel>> getUserDepsByUserId(UserIdDTO param){
        BaseResult<List<SysUserDepModel>> res = new BaseResult<>();
        if(param ==null || StringUtils.isBlank(param.getUserId())){
            res.setMsg("请先选择用户");
        }else{
            List<SysUserDepModel> userDepsInfo = this.baseService.getUserDepsInfo(param.getUserId());
            res.setData(userDepsInfo);
            res.toSuccess();
        }
        return res;
    }

    /**
     * 新增用户组织关系对象，组织成员
     * @param param
     * @param request
     * @param response
     * @return
     */
    @PostMapping
    @ApiOperation(value="新增用户组织关系对象，组织成员",notes="")
    @PreAuthorize("hasAnyAuthority('SysDepUser:add') || hasRole('"+ BaseConstants.ADMINISTRATOR_ROLE_CODE +"') ")
    public BaseResult<SysUserDepModel> add(@Valid @RequestBody SysUserDepModel param, HttpServletRequest request, HttpServletResponse response){
        BaseResult<SysUserDepModel> res = new BaseResult<>();
        if(!depIsEnable(param.getDepId())){
            res.setMsg("没有指定组织的权限");
        }else{
            res = super.add(param);
        }
        return res;
    }



    /**
     * 获取用户组织关系对象，组织成员详情
     * @param id
     * @param response
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation(value="获取用户组织关系对象，组织成员详情",notes="")
    @ApiParam(name = "id",type = "Serializable",required = true)
    @PreAuthorize("hasAnyAuthority('SysDepUser:info') || hasRole('"+ BaseConstants.ADMINISTRATOR_ROLE_CODE +"') ")
    public BaseResult<SysUserDepModel> info(@PathVariable("id") Serializable id, HttpServletRequest request, HttpServletResponse response){
        BaseResult<SysUserDepModel> res = new BaseResult<>();
        res = super.info(id);
        return res;
    }

    /**
     * 修改用户组织关系对象，组织成员
     * @param param
     * @param request
     * @param response
     * @return
     */
    @PutMapping
    @ApiOperation(value="修改用户组织关系对象，组织成员",notes="")
    @PreAuthorize("hasAnyAuthority('SysDepUser:edit') || hasRole('"+ BaseConstants.ADMINISTRATOR_ROLE_CODE +"') ")
    public BaseResult<SysUserDepModel> edit(@RequestBody SysUserDepModel param,HttpServletRequest request, HttpServletResponse response){
        BaseResult<SysUserDepModel> res = new BaseResult<>();
        if(!depIsEnable(param.getDepId())){
            res.setMsg("没有指定组织的权限");
        }else{
            res =  super.edit(param);
        }
        return res;
    }

    /**
     * 删除用户组织关系对象，组织成员
     * @param ids
     * @param request
     * @param response
     * @return
     */
    @DeleteMapping
    @ApiOperation(value="删除用户组织关系对象，组织成员",notes="注意参数是数字，就算单个，也要以数字的形式传递")
    @PreAuthorize("hasAnyAuthority('SysDepUser:del') || hasRole('"+ BaseConstants.ADMINISTRATOR_ROLE_CODE +"') ")
    public BaseResult<SysUserDepModel> delete(@RequestBody String[] ids, HttpServletRequest request, HttpServletResponse response){
        BaseResult<SysUserDepModel> res = new BaseResult<>();
        res = super.delete(ids);
        return res;
    }

    /**
     * 是否有组织权限
     * @param depId
     * @return
     */
    protected boolean depIsEnable(String depId){
        boolean bln = false;
        try {
            bln = DepIdsUtil.getAllPermissionDepIds().contains(depId);
        } catch (Exception e) {
            //e.printStackTrace();
        }
        return bln;
    }

    //************  ******* 用户自身相关  无需权限   **********     *********//

    /**
     * 获取用户自身 的组织信息
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/selfDeps")
    @ApiOperation(value="获取用户自身 所在组织的成员信息",notes="",tags = "用户自身相关接口")
    public BaseResult<List<SysUserDepModel>> getUserSelfDeps(HttpServletRequest request, HttpServletResponse response){
        BaseResult<List<SysUserDepModel>> res = new BaseResult<>();
        RequestUserInfoModel requestUserInfoModel = RequestUserInfoUtil.getRequestUserInfoModel();
        if(requestUserInfoModel ==null){
            res.setMsg("用户登录已过期，请重新登录");
        }else{
            List<SysUserDepModel> userDepsInfo = this.baseService.getUserDepsInfo(requestUserInfoModel.getUserId());
            res.setData(userDepsInfo);
            res.toSuccess();
        }
        return res;
    }


    /**
     * 获取组织结构树
     * @return
     */
    @GetMapping("/tree")
    @ApiOperation(value = "获取组织结构树", notes = "")
    public BaseResult<List<SysDepartmentVO>> tree(SysDepartmentVO vo) {
        BaseResult<List<SysDepartmentVO>> res = new BaseResult<>();
        // if(RequestUserInfoUtil.getRequestUserInfoModel().get)
        List<String> rolesCatchByUserId = authenticationCache.getRolesCatchByUserId(RequestUserInfoUtil.getRequestUserInfoModel().getUserId());
        List<SysDepartmentVO> tree = null;
        if(rolesCatchByUserId!=null && rolesCatchByUserId.contains(SysConstants.ROLE_PREFIX+SysConstants.ADMINISTRATOR_ROLE_CODE)){
            tree = this.departmentService.tree();
        }else{
            SysDepartmentModel model = new SysDepartmentModel();
            if(vo !=null && StringUtils.isNotBlank(vo.getId())){
                Set<String> currentDepIds = DepIdsUtil.getCurrentDepIds();
                model.set_depIds(currentDepIds);
            }else{
                Set<String> currentDepIds = DepIdsUtil.getAllPermissionDepIds();
                model.set_depIds(currentDepIds);
            }
            tree = this.departmentService.tree(model);
        }
        return res.toSuccess().setData(tree);

    }

}

